package com.atguigu.juc;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建执行线程的方式三： 实现Callable接口，相较于Runnable接口方式，可以指定泛型，接口有返回值，并可以抛出异常
 *
 * 执行callable方式，需要FutureTask实现类支持，用于接收返回结果, FutureTask是Future接口实现类
 */
public class TestCallable {

    public static void main(String[] args) {
        ThreadDemo1 threadDemo = new ThreadDemo1();

        FutureTask<Integer> futureTask = new FutureTask<>(threadDemo);
        new Thread(futureTask).start();

        Integer sum = null;
        try {
            sum = futureTask.get();  // FutureTask也可以用于闭锁
            System.out.println("futureTask返回结果=" + sum);
            System.out.println("==========================");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}


class ThreadDemo1 implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum;

    }
}

/*
class ThradDemo implements Runnable{

    @Override
    public void run() {

    }
}
*/
